<template>
  <view class="login-container">
    <!-- 顶部背景区域 -->
    <view class="bg-area">
      <image class="bg-image" src="/static/images/agriculture-bg.png" mode="aspectFill"></image>
      <view class="overlay"></view>
      <view class="platform-info">
        <image class="logo" src="/static/images/logo.png" mode="aspectFit"></image>
        <text class="platform-name">智慧农业环境监测平台</text>
        <text class="platform-slogan">科技赋能农业 · 数据驱动未来</text>
      </view>
    </view>

    <!-- 登录表单区域 -->
    <view class="form-card">
      <view class="form-header">
        <text class="form-title">账号登录</text>
        <text class="form-subtitle">欢迎回来，请登录您的账号</text>
      </view>

      <view class="form-body">
        <!-- 用户名输入框 -->
        <view class="input-group">
          <text class="input-label">用户名</text>
          <view class="input-wrapper" :class="{ 'input-focus': usernameFocus }">
            <image class="icon" src="/static/login/icons8-用户-50.png" mode="aspectFit"></image>
            <input
              class="input"
              type="text"
              v-model="loginForm.username"
              placeholder="请输入用户名"
              @focus="usernameFocus = true"
              @blur="usernameFocus = false"
            />
          </view>
        </view>

        <!-- 密码输入框 -->
        <view class="input-group">
          <text class="input-label">密码</text>
          <view class="input-wrapper" :class="{ 'input-focus': passwordFocus }">
            <image class="icon" src="/static/login/icons8-密码-30.png" mode="aspectFit"></image>
            <input
              class="input"
              :type="showPassword ? 'text' : 'password'"
              v-model="loginForm.password"
              placeholder="请输入密码"
              @focus="passwordFocus = true"
              @blur="passwordFocus = false"
            />
            <text 
              class="iconfont" 
              :class="showPassword ? 'icon-eye' : 'icon-eye-close'"
              @tap="togglePasswordVisibility"
            ></text>
          </view>
        </view>

        <!-- 记住密码和忘记密码 -->
        <view class="options-row">
          <!-- 记住密码复选框 -->
          <view class="remember-option" @tap="toggleRemember">
            <view class="checkbox" :class="{ 'checked': loginForm.remember }">
              <image 
                v-if="loginForm.remember"
                class="check-icon"
                src="/static/login/icons8-复选标记-50.png" 
                mode="aspectFit"
              ></image>
            </view>
            <text class="remember-text">记住密码</text>
          </view>
          <text class="forgot-password" @tap="goToForgotPassword">忘记密码?</text>
        </view>

        <!-- 登录按钮 -->
        <button class="login-button" :disabled="isSubmitting" @tap="handleLogin">
          <text v-if="isSubmitting">登录中...</text>
          <text v-else>登录</text>
        </button>

        <!-- 其他登录方式 -->
        <view class="other-login-methods" v-if="showOtherLoginMethods">
          <view class="divider">
            <view class="line"></view>
            <text class="divider-text">其他登录方式</text>
            <view class="line"></view>
          </view>
          
          <view class="social-login">
            <view class="social-icon wechat" @tap="socialLogin('wechat')">
              <image class="social-image" src="/static/login/icons8-微信-50.png" mode="aspectFit"></image>
            </view>
            <view class="social-icon alipay" @tap="socialLogin('alipay')">
              <image class="social-image" src="/static/login/icons8-支付宝-50.png" mode="aspectFit"></image>
            </view>
          </view>
        </view>

        <!-- 注册账号 -->
        <view class="register-link">
          <text class="register-text">还没有账号? </text>
          <text class="register-action" @tap.stop="goToRegister">立即注册</text>
        </view>
      </view>
    </view>

    <!-- 底部版权信息 -->
    <view class="footer">
      <text class="copyright">© {{ currentYear }} 智慧农业环境监测平台 版权所有</text>
    </view>
  </view>
</template>

<script setup>
import { ref, reactive, onMounted, computed } from 'vue';

// 响应式状态
const loginForm = reactive({
  username: '',
  password: '',
  remember: false
});

const usernameFocus = ref(false);
const passwordFocus = ref(false);
const showPassword = ref(false);
const isSubmitting = ref(false);
const showOtherLoginMethods = ref(true);
const currentYear = computed(() => new Date().getFullYear());

// 生命周期钩子
onMounted(() => {
  checkSavedCredentials();
});

// 方法
const togglePasswordVisibility = () => {
  showPassword.value = !showPassword.value;
};

const toggleRemember = () => {
  loginForm.remember = !loginForm.remember;
};

const handleLogin = async () => {
  // 表单验证
  if (!loginForm.username.trim()) {
    uni.showToast({
      title: '请输入用户名',
      icon: 'none'
    });
    return;
  }
  
  if (!loginForm.password) {
    uni.showToast({
      title: '请输入密码',
      icon: 'none'
    });
    return;
  }
  
  try {
    isSubmitting.value = true;
    
    // 调用云函数进行登录验证
    const { result } = await uniCloud.callFunction({
      name: 'login',
      data: {
        username: loginForm.username.trim(),
        password: loginForm.password
      }
    });
    
    // 处理登录结果
    if (result.code === 200) {
      // 如果选择了记住密码，保存凭据
      if (loginForm.remember) {
        saveCredentials();
      } else {
        clearCredentials();
      }
      
      // 保存用户信息到本地存储
      uni.setStorageSync('userInfo', result.data);
      
      // 登录成功提示
      uni.showToast({
        title: '登录成功',
        icon: 'success'
      });
      
      // 延迟跳转到首页
      setTimeout(() => {
        uni.switchTab({
          url: '/pages/index/index'
        });
      }, 1500);
    } else {
      // 显示错误信息
      uni.showToast({
        title: result.msg,
        icon: 'none'
      });
    }
    
  } catch (error) {
    console.error('登录错误:', error);
    uni.showToast({
      title: '登录失败，请稍后重试',
      icon: 'none'
    });
  } finally {
    isSubmitting.value = false;
  }
};

const saveCredentials = () => {
  try {
    uni.setStorageSync('savedUsername', loginForm.username);
    // 注意：实际应用中应加密存储密码或使用token
    uni.setStorageSync('savedPassword', loginForm.password);
    uni.setStorageSync('rememberPassword', true);
  } catch (e) {
    console.error('保存凭据失败:', e);
  }
};

const clearCredentials = () => {
  try {
    uni.removeStorageSync('savedUsername');
    uni.removeStorageSync('savedPassword');
    uni.removeStorageSync('rememberPassword');
  } catch (e) {
    console.error('清除凭据失败:', e);
  }
};

const checkSavedCredentials = () => {
  try {
    const remember = uni.getStorageSync('rememberPassword');
    if (remember) {
      const username = uni.getStorageSync('savedUsername');
      const password = uni.getStorageSync('savedPassword');
      
      if (username) {
        loginForm.username = username;
        loginForm.password = password || '';
        loginForm.remember = true;
      }
    }
  } catch (e) {
    console.error('读取凭据失败:', e);
  }
};

const goToForgotPassword = () => {
  uni.navigateTo({
    url: '/pages/forgot-password/index'
  });
};

const goToRegister = () => {
  uni.navigateTo({
    url: '/pages/register/register'
  });
};

const socialLogin = (platform) => {
  uni.showToast({
    title: `${platform}登录功能开发中`,
    icon: 'none'
  });
};
</script>

<style>
/* 全局样式 */
page {
  background-color: #f5f7fa;
  font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Oxygen, Ubuntu, Cantarell, 'Open Sans', 'Helvetica Neue', sans-serif;
}

.login-container {
  display: flex;
  flex-direction: column;
  min-height: 100vh;
}

/* 顶部背景区域 */
.bg-area {
  position: relative;
  height: 35vh;
  overflow: hidden;
}

.bg-image {
  width: 100%;
  height: 100%;
}

.overlay {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: linear-gradient(to bottom, rgba(0, 0, 0, 0.3), rgba(0, 0, 0, 0.5));
}

.platform-info {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  display: flex;
  flex-direction: column;
  align-items: center;
  width: 100%;
}

.logo {
  width: 80px;
  height: 80px;
  border-radius: 20px;
  margin-bottom: 15px;
}

.platform-name {
  color: #ffffff;
  font-size: 22px;
  font-weight: bold;
  margin-bottom: 8px;
  text-shadow: 0 2px 4px rgba(0, 0, 0, 0.2);
}

.platform-slogan {
  color: rgba(255, 255, 255, 0.9);
  font-size: 14px;
  text-shadow: 0 1px 2px rgba(0, 0, 0, 0.2);
}

/* 表单卡片 */
.form-card {
  margin: -20px 20px 20px;
  padding: 25px;
  background-color: #ffffff;
  border-radius: 15px;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.08);
  position: relative;
  z-index: 10;
}

.form-header {
  margin-bottom: 25px;
}

.form-title {
  font-size: 22px;
  font-weight: bold;
  color: #333333;
  margin-bottom: 8px;
  display: block;
}

.form-subtitle {
  font-size: 14px;
  color: #888888;
  display: block;
}

/* 输入框样式 */
.input-group {
  margin-bottom: 20px;
}

.input-label {
  font-size: 14px;
  color: #333333;
  margin-bottom: 8px;
  display: block;
  font-weight: 500;
}

.input-wrapper {
  display: flex;
  align-items: center;
  height: 50px;
  border: 1px solid #e0e0e0;
  border-radius: 8px;
  padding: 0 15px;
  background-color: #f9f9f9;
  transition: all 0.3s;
}

.input-focus {
  border-color: #4CAF50;
  background-color: #ffffff;
  box-shadow: 0 0 0 2px rgba(76, 175, 80, 0.1);
}

.input {
  flex: 1;
  height: 50px;
  font-size: 15px;
  padding-left: 10px;
  background-color: transparent;
}

/* 图标样式 */
.iconfont {
  font-family: "iconfont";
  color: #999999;
  font-size: 20px;
}

/* 图片图标样式 */
.icon {
  width: 20px;
  height: 20px;
  margin-right: 8px;
}

/* 记住密码和忘记密码 */
.options-row {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 25px;
}

.remember-option {
  display: flex;
  align-items: center;
}

.checkbox {
  width: 18px;
  height: 18px;
  border: 1px solid #d9d9d9;
  border-radius: 4px;
  margin-right: 8px;
  display: flex;
  align-items: center;
  justify-content: center;
}

.checked {
  background-color: #4CAF50;
  border-color: #4CAF50;
}

.checked .icon-check {
  color: #ffffff;
  font-size: 14px;
}

.remember-text {
  font-size: 14px;
  color: #666666;
}

.forgot-password {
  font-size: 14px;
  color: #4CAF50;
}

/* 登录按钮 */
.login-button {
  width: 100%;
  height: 50px;
  line-height: 50px;
  background: linear-gradient(135deg, #4CAF50, #2E7D32);
  color: #ffffff;
  font-size: 16px;
  font-weight: 500;
  border-radius: 8px;
  margin-bottom: 20px;
  box-shadow: 0 4px 10px rgba(76, 175, 80, 0.2);
  border: none;
}

.login-button:active {
  transform: translateY(1px);
  box-shadow: 0 2px 6px rgba(76, 175, 80, 0.2);
}

.login-button[disabled] {
  background: linear-gradient(135deg, #a5d6a7, #81c784);
  opacity: 0.8;
}

/* 其他登录方式 */
.other-login-methods {
  margin-top: 10px;
  margin-bottom: 20px;
  position: relative;
  z-index: 1;
}

.divider {
  display: flex;
  align-items: center;
  margin-bottom: 20px;
}

.line {
  flex: 1;
  height: 1px;
  background-color: #e0e0e0;
}

.divider-text {
  padding: 0 15px;
  font-size: 14px;
  color: #999999;
}

.social-login {
  display: flex;
  justify-content: center;
  gap: 30px;
}

.social-icon {
  width: 50px;
  height: 50px;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
}

.wechat {
  background-color: #07C160;
}

.alipay {
  background-color: #1677FF;
}

.social-icon .iconfont {
  color: #ffffff;
  font-size: 28px;
}

/* 注册链接 */
.register-link {
  text-align: center;
  margin-top: 15px;
  padding: 10px 0;
  position: relative;
  z-index: 2;
}

.register-text {
  font-size: 14px;
  color: #666666;
}

.register-action {
  font-size: 14px;
  color: #4CAF50;
  font-weight: 500;
  padding: 5px 10px;
  position: relative;
  z-index: 2;
}

/* 底部版权信息 */
.footer {
  margin-top: auto;
  padding: 20px 0;
  text-align: center;
}

.copyright {
  font-size: 12px;
  color: #999999;
}
</style>

// 在样式部分注释支付宝字体图标
/*
.icon-alipay:before {
  content: "\e87c";
}
*/
.social-image {
  width: 40px;
  height: 40px;
}

/* 注释原有微信图标样式 */
/*
.icon-wechat:before {
  content: "\e883";
}
*/
.check-icon {
  width: 18px;
  height: 18px;
}